#include "Util.h"
#include <filesystem>
#include <cassert>
#include <fstream>

namespace util {

bool File::create(const std::string & name){
	if(!File::exists(name)){
		std::ofstream{name};
		return true;
	}
	return false;
}

bool File::remove(const std::string & name){
	std::filesystem::path p = name;
	return std::filesystem::remove(p);
}
bool File::exists(const std::string & name){
	std::filesystem::path p = name;
	return std::filesystem::exists(p);
}
int File::writeAndFlushAsBinary(const std::string & name, int number){
  std::ofstream ofs(name, std::ios_base::binary|std::ios_base::out);
  if(!ofs.is_open()){
    return -1;
  }
  ofs.write(reinterpret_cast<const char*>(&number), sizeof(int));
  ofs.flush();
  return sizeof(int);
}
int File::readAsBinary(const std::string & name, int * number){
  std::ifstream ifs(name, std::ios_base::binary|std::ios_base::in);
  if(!ifs.is_open()){
    return -1;
  }
  ifs.read(reinterpret_cast<char*>(number), sizeof(int));
  return sizeof(int);
}

}//end namespace util


void test_util_file(){
	const char * fileName = "breakpoint.file";
	if(util::File::exists(fileName)){
		assert(true == util::File::remove(fileName));
	}
	assert(false == util::File::exists(fileName));
	assert(false == util::File::remove(fileName));


	assert(util::File::create(fileName));
	assert(util::File::exists(fileName));
	assert(util::File::remove(fileName));
	assert(false == util::File::exists(fileName));

  assert(4 == util::File::writeAndFlushAsBinary(fileName, 0x31));
  int number = 0;
  assert(4 == util::File::readAsBinary(fileName, &number));
  assert(number == 0x31);

  //assert(util::File::remove(fileName));
}

